import twitter, time, threading, sys
import twitter.oauth_dance

twapp_name = "daft-bot"
consumer_key = '2As7ZLSVR0UreeqJjuQJsw'
consumer_secret = 'CNnBOWU0yH2B0a8J7mCsXENWsZFwpmYc1VTCQVnF94'
alreadyseentweets = []

def getToken():
	global consumer_key, consumer_secret, twapp_name
	return twitter.oauth_dance.oauth_dance(twapp_name,consumer_key,consumer_secret)

tweetime = time.time()
twonline = False
waittime = 60
lastmention = 0
t = None


def httpdate(now):
	stamp = time.mktime(now.timetuple())
	return formatdate(
	    timeval     = stamp,
	    localtime   = False,
	    usegmt      = True
	)

def checkmentions(daft):
	global twitter, waittime, alreadyseentweets, firsttime
	print "Checking timeline"
	for update in twitter.Twitter(auth=oauth).statuses.mentions(since=lastmention):
		if update['id'] not in alreadyseentweets:
			print update['user']['screen_name']+": "+update['text']
			if len(alreadyseentweets)>0:
				daft.boom(update['text'].replace("@dobbybot",""),update['user']['screen_name'],"twitter")
			alreadyseentweets.append(update['id'])
			daft.setc("seentwittermentions",alreadyseentweets)
	firsttime = False

class twthread( threading.Thread ):
	def __init__(self,daft):
		super(twthread, self).__init__()
		self.daft = daft
		self._stop = threading.Event()
	def stop (self):
		self._stop.set()

	def stopped (self):
		return self._stop.isSet()

	def run ( self ):
		print "running twitter thread"
		global waittime
		while not self.stopped():
			print "checking for tweet mentions..."
			checkmentions(self.daft)
			time.sleep(waittime)


def sendtweet(update):
	global oauth
	if len(update) < 140:
		twitter.Twitter(auth=oauth).statuses.update(status=update)
		print "tweet posted: "+update
	else:
		print "tweet too long"


def start(daft):
	global oauth,tokentuple,alreadyseentweets, t
	if daft.getc("twittertoken"):
		tokentuple = daft.getc("twittertoken")
	else:
		tokentuple = getToken()
		daft.setc("twittertoken",tokentuple)
	oauth = twitter.OAuth(tokentuple[0],tokentuple[1],consumer_key, consumer_secret)

	if daft.getc("seentwittermentions"):
		alreadyseentweets = daft.getc("seentwittermentions")

	print "checking for twitter thread"
	if "twitter" in sys.argv:
		print "starting twitter thread"
		t = twthread(daft)
		t.start()
	return True

def tick():
	pass
def say(daft,r,who,w):
	if "twitter" in w.split(","):
		global twapi
		update = "@"+who+" "+r
		if len(update) < 140:
			sendtweet(update)
			print "posted: "+update
	return True
def stop():
	global t
	t.stop()
print "twitter loaded"
